package com.tind.wyf.baselib.base.nav;

import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.IdRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import com.tind.wyf.baselib.R;
import com.tind.wyf.baselib.base.BaseFragment;
import com.tind.wyf.baselib.widget.BorderShape;

import java.util.List;

public class NavFragment extends BaseFragment implements View.OnClickListener {
    private Context mContext;
    private FragmentManager mFragmentManager;
    private int mContainerId;

    private OnNavigationReselectListener mOnNavigationReselectListener;
    private NavigationButton mCurrentNavButton;
    private LinearLayout mNavBar;
    private Bundle bundle;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_nav;
    }

    @Override
    protected void initView(View view) {
        ShapeDrawable lineDrawable = new ShapeDrawable(new BorderShape(new RectF(0, 1, 0, 0)));
        lineDrawable.getPaint().setColor(getResources().getColor(R.color.black));
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
                new ColorDrawable(getResources().getColor(R.color.white)),
                lineDrawable
        });
        view.setBackground(layerDrawable);
        mNavBar = (LinearLayout) view.findViewById(R.id.ll_fragment_button);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        if (v instanceof NavigationButton) {
            NavigationButton nav = (NavigationButton) v;
            bundle.putInt("fragment", nav.getIndex());
            doSelect(nav);
        }
    }

    /**
     * <>
     * FrameLayout布局
     * <FrameLayout
     *  android:id="@+id/main_container"
     *  android:layout_width="match_parent"
     *  android:layout_height="0dp"
     *  android:layout_weight="1" />
     * </>
     * <p>
     * 设置frament界面
     *
     * @param context         上下文
     * @param fragmentManager frament管理器
     * @param contentId       内容存放布局id（FrameLayout布局id）
     * @param bundle           Bundle可以直接设置从上一界面传过来得数据
     * @param listener
     */
    public void setup(Context context, FragmentManager fragmentManager, @IdRes int contentId, Bundle bundle,
                      OnNavigationReselectListener listener) {
        mContext = context;
        mFragmentManager = fragmentManager;
        mContainerId = contentId;
        mOnNavigationReselectListener = listener;
        this.bundle = bundle;
        this.bundle.putInt("fragment", 0);
        getTabBtn();
        // do clear
        clearOldFragment();
        // do select first
        doSelect((NavigationButton) mNavBar.getChildAt(0));
    }

    public void setDot(int index, int count) {
        NavigationButton button = (NavigationButton) mNavBar.getChildAt(index);
        button.showRedDot(count);
    }

    public void select(int index) {
        if ((NavigationButton) mNavBar.getChildAt(index) != null)
            doSelect((NavigationButton) mNavBar.getChildAt(index));
    }

    @SuppressWarnings("RestrictedApi")
    private void clearOldFragment() {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        List<Fragment> fragments = mFragmentManager.getFragments();
        if (transaction == null || fragments == null || fragments.size() == 0)
            return;
        boolean doCommit = false;
        for (Fragment fragment : fragments) {
            if (fragment != this) {
                transaction.remove(fragment);
                doCommit = true;
            }
        }
        if (doCommit)
            transaction.commitNow();
    }

    private void doSelect(NavigationButton newNavButton) {

        NavigationButton oldNavButton = null;
        if (mCurrentNavButton != null) {
            oldNavButton = mCurrentNavButton;
            if (oldNavButton == newNavButton) {
                onReselect(oldNavButton);
                return;
            }
//            onReselect(oldNavButton);
            oldNavButton.setSelected(false);
        }
        newNavButton.setSelected(true);
        doTabChanged(oldNavButton, newNavButton);
        mCurrentNavButton = newNavButton;
    }

    private void doTabChanged(NavigationButton oldNavButton, NavigationButton newNavButton) {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (oldNavButton != null) {
            if (oldNavButton.getFragment() != null) {
                ft.detach(oldNavButton.getFragment());
            }
        }
        if (newNavButton != null) {
            if (newNavButton.getFragment() == null) {
                Fragment fragment = mFragmentManager.getFragmentFactory()
                        .instantiate(mContext.getClassLoader()
                                , newNavButton.getClx().getName());
                fragment.setArguments(bundle);
                Log.i("doTabChanged",  fragment.getClass().getCanonicalName());
//                Fragment fragment = Fragment.instantiate(mContext,
//                        newNavButton.getClx().getName(), bundle);
                ft.add(mContainerId, fragment, newNavButton.getTag());
                newNavButton.setFragment(fragment);
            } else {
                ft.attach(newNavButton.getFragment());
            }
        }
        ft.commit();
    }

    private void onReselect(NavigationButton navigationButton) {
        OnNavigationReselectListener listener = mOnNavigationReselectListener;
        if (listener != null) {
            listener.onReselect(navigationButton);
        }
    }

    /**
     *
     */
    public void getTabBtn() {
        FragmentBuilder bean = (FragmentBuilder) bundle.getSerializable("fragmentBuilder");
        int[] icons = bean.getIcons();
        String[] titleBar = bean.getTitleBar();
        List<Class> clx = bean.getClx();
        if (icons == null) {
            icons = new int[titleBar.length];
        }
        for (int i = 0; i < titleBar.length; i++) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
            NavigationButton mNavBut = new NavigationButton(mContext);
            mNavBut.setLayoutParams(lp);
            mNavBut.init(i, icons[i], titleBar[i], clx.get(i));
            mNavBut.setOnClickListener(this);
            mNavBar.addView(mNavBut);
        }
        bundle.remove("fragmentBean");
    }

    public interface OnNavigationReselectListener {
        void onReselect(NavigationButton navigationButton);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
